package org.onvivals.app.websocket;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FunASRClient extends WebSocketClient {

    private static final ConcurrentHashMap<String, String> sessionPools = new ConcurrentHashMap<>();

    public FunASRClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        System.out.println("Connected to FunASR server.");
    }

    @Override
    public void onMessage(String message) {
        System.out.println("Recognition result: " + message);
        if (JSONUtil.isTypeJSON(message)){
            JSONObject jsonObject = JSONUtil.parseObj(message);
            if (jsonObject.containsKey("stamp_sents")){
                System.out.println("jsonObject: " + jsonObject);
                String wavName = jsonObject.getStr("wav_name");
                String content = jsonObject.getStr("text");
				//{"is_final":true,"mode":"2pass-offline","stamp_sents":[{"end":1075,"punc":"。","start":50,"text_seg":"这 样 还 是 会 跳 不 对","ts_list":[[50,150],[150,270],[270,370],[370,470],[470,610],[610,750],[750,870],[870,1075]]}],"text":"这样还是会跳不对。","timestamp":"[[50,150],[150,270],[270,370],[370,470],[470,610],[610,750],[750,870],[870,1075]]","wav_name":"ZTQtYjAtNjMtYjItZmMtNDQ="}
                sessionPools.put(wavName,content);
				System.out.println("sessionPools-content: " + sessionPools.get(wavName));
            }
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Connection closed. Reason: " + reason);
    }

    @Override
    public void onError(Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }

    // Send audio data as byte chunks
    public void sendAudioData(byte[] audioBytes) {
        this.send(ByteBuffer.wrap(audioBytes));
    }

    // Send configuration in JSON
    public void sendConfig(Map<String, Object> config) {
        String configJson = JSONUtil.toJsonStr(config);
        System.out.println(configJson);
        if (config.containsKey("wav_name")){
            sessionPools.remove(Convert.toStr(config.get("wav_name")));
        }
        this.send(configJson);
    }
    public void end(Map<String, Object> config) {
        String configJson = JSONUtil.toJsonStr(config);
        this.send(configJson);
    }

    public String text(String wavName) {
        return sessionPools.get(wavName);
    }
    public String clean(String wavName) {
        return sessionPools.remove(wavName);
    }

}
